import axios from 'axios'
import {
  Notify,
  Toast
} from 'vant'
import cfg from '@/config'
import {
  addPending,
  removePending
} from '@/utils/padding'
import {
  LreItem,
  LgetItem
} from '@/utils/storage'
import statusCode from '@/config/statusCode'
import router from '@/router'
import {
  wx,
  wxInit
} from "@/utils/jssdkInit.js";

axios.defaults.baseURL = `${cfg.host}${cfg.port}${cfg.baseUrl}`
// axios.defaults.baseURL = ''
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.headers.get['Accept'] = 'application/json'
axios.defaults.timeout = 20000
axios.defaults.withCredentials = true
let ajaxTimes = 0

export function startLoading() {
  if (ajaxTimes === 0) {
    Toast.loading({
      forbidClick: true,
      duration: 0
    });
  }
  ajaxTimes++
}
export function closeLoading() {
  if (ajaxTimes <= 0) return
  ajaxTimes--
  if (ajaxTimes === 0) {
    Toast.clear()
    ajaxTimes = 0
  }
}

axios.interceptors.request.use(
  config => {
    startLoading()
    LgetItem('jwtToken') && (config.headers['Token'] = LgetItem('jwtToken'))
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

axios.interceptors.response.use(res => {
  closeLoading()
  const data = res.data;
  const status = res.status;
  // 响应拦截
  if (status == 200) {
    if (data) {
      const serveCode = data.code;
      if (serveCode === 0) {
        return Promise.resolve(data.data);
      } else {
        if (serveCode == -1) {
          Notify({
            type: 'danger',
            message: data.desc,
            duration: 1000,
          })
          return Promise.reject(data);
        }
      }
    }
  } else {
    Notify({
      type: 'danger',
      message: res.desc,
      duration: 1000,
    })
    return Promise.reject(data);
  }
}, err => {
  console.log(err)
  closeLoading()
  if(err.response.status == 401){//token，"Unauthorized"
    LreItem('jwtToken')
    Notify({
      type:'error',
      message:'登录已过期',
      duration: 1000,
      onClose:()=>{
        router.replace({
          path:'/',
          query:{
            id:LgetItem('voteId')
          }
        })
      }
    })
  }
  return Promise.reject(err)
})
export default function (options) {
  let params = {
    method: options.method,
    url: options.url,
    data: options.params,
    ...options.other
  }
  if (params.method.toLowerCase() === 'get') {
    params.params = params.data
    delete params.data
  }
  return axios(params)
}